#已设置忽略  PEP8.E265
"""人脸与眼睛识别，显示别人脸再识别眼睛，增加精确度"""
import cv2
import numpy as np
#change

def catchUsbVideo(window_name, camera_idx):
    cv2.namedWindow(window_name)

    # 视频来源，可以来自一段已存好的视频，也可以直接来自USB摄像头
    cap = cv2.VideoCapture(camera_idx)

    # 告诉OpenCV使用人脸识别分类器
    face_classfier = cv2.CascadeClassifier("../cascades/haarcascade_frontalface_default.xml")
    eye_classfier = cv2.CascadeClassifier("../cascades/haarcascade_eye.xml")
    # 识别出人脸后要画的边框的颜色，RGB格式
    color = (0, 255, 0)

    while cap.isOpened():
        ok, frame = cap.read()  # 读取一帧数据
        if not ok:
            break

            # 将当前帧转换成灰度图像
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # 人脸检测，1.2和2分别为图片缩放比例和需要检测的有效点数
        face_rects = face_classfier.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))

        if len(face_rects) > 0:  # 大于0则检测到人脸
            for faceRect in face_rects:  # 单独框出每一张人脸
                x, y, w, h = faceRect
                cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 3) #5控制绿色框的粗细
        for (x, y, w, h) in face_rects:
            #cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
            roi_gray = gray[y: y + h, x: x + w]
            roi_color = frame[y : y + h, x : x + w]
            eyes = eye_classfier.detectMultiScale(roi_gray)
            for (ex, ey, ew, eh) in eyes:
                cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 0, 255), 2)

        # 显示图像
        cv2.imshow(window_name, frame)
        c = cv2.waitKey(200)
        if c & 0xFF == ord('q'):
            break

            # 释放摄像头并销毁所有窗口
    cap.release()
    cv2.destroyAllWindows()


if __name__ == '__main__':
    catchUsbVideo("FaceRect", 0)
